import { defineStore } from 'pinia'

// 检查本地存储中的主题偏好
const getInitialTheme = () => {
  const savedTheme = localStorage.getItem('theme')
  if (savedTheme) {
    return savedTheme === 'dark'
  }
  // 默认根据系统偏好设置
  return window.matchMedia('(prefers-color-scheme: dark)').matches
}

export const useThemeStore = defineStore('theme', () => {
  // 使用ref定义状态
  const isDark = ref(getInitialTheme())

  // 应用主题的函数
  const applyTheme = () => {
    document.documentElement.classList.toggle('dark', isDark.value)
  }

  // 切换主题的函数
  const toggleTheme = () => {
    isDark.value = !isDark.value
    localStorage.setItem('theme', isDark.value ? 'dark' : 'light')
    applyTheme()
  }

  // 导出状态和方法
  return {
    isDark,
    toggleTheme,
    applyTheme
  }
})